package logic

import (
	"context"
	"github.com/golang-jwt/jwt/v4"
	"time"

	"go-zero-demo/mall/user/rpc/internal/svc"
	"go-zero-demo/mall/user/rpc/types/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *user.LoginReq) (*user.LoginResp, error) {
	info, err := l.svcCtx.StudentModel.FindOne(l.ctx, in.Id)
	if err != nil {
		return nil, err
	}
	iat := time.Now().Unix()
	seconds := l.svcCtx.Config.Token.AccessExpire
	userId := info.Sno
	token, err := l.getJwtToken(l.svcCtx.Config.Token.AccessSecret, iat, seconds, userId)

	return &user.LoginResp{
		Id:    info.Sno,
		Token: token,
	}, nil
}

func (l *LoginLogic) getJwtToken(secretKey string, iat, seconds int64, userId string) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["userId"] = userId
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}
